<?php
/**
 * Created by 无所谓已
 * User: Administrator
 * Date: 2025-08-22
 * Time: 22:20
 */

namespace plugin\csauto\app\process;


use plugin\csauto\app\model\DownloaderModel;
use plugin\csauto\app\model\TorrentListModel;
use plugin\csauto\app\model\TorrentTaskModel;
use plugin\csauto\app\service\downloader\DownloaderWorkService;
use plugin\csauto\app\service\RssWorkService;
use plugin\csauto\app\service\SystemService;
use plugin\csauto\app\service\TorrentListService;
use plugin\csauto\app\service\HelperService;
use support\Log;
use Workerman\Crontab\Crontab;
use Workerman\Timer;

/**
 * Class DownloaderAddTaskProcess
 * 步骤3
 * 检查下载器可执行的任务信息,进行任务发布的操作
 *
 * @package plugin\csauto\app\process
 */
class DownloaderAddTaskProcess
{
    // 定时器句柄/ID
    protected $timer;
    protected $wechatTimer;
    protected $torrentTaskMaxNum = 5;

    // 时间间隔 (单位: 秒, 默认5秒)
    protected $interval = 50;

    public function onWorkerStart()
    {
        if (getenv('WORK_DEBUG')) return true;
        $this->timer = Timer::add($this->interval, function () {
            try {
                // 这里执行系统预设的定时任务事件
                $this->run();
            } catch (\Throwable $e) {
                echo 'ERROR[DownloaderAddTaskProcess]: ' . $e->getMessage() . PHP_EOL;
            }
        });

        return true;
    }

    public function run()
    {
//        echo "开始进行 ==>>>>>> DownloaderAddTaskProcess" . PHP_EOL;
        addlog('下载器-新增任务', 'start');
        
        // 获取活跃任务的判断参数
        $activeSizeThreshold = SystemService::getConfig(SystemService::ACTIVE_TASK_SIZE_THRESHOLD);
        $activeCountLimit = SystemService::getConfig(SystemService::ACTIVE_TASK_COUNT_LIMIT);
        
        // 如果未配置或配置无效，使用默认值
        if (!$activeSizeThreshold || $activeSizeThreshold <= 0) $activeSizeThreshold = 2;
        if (!$activeCountLimit || $activeCountLimit <= 0) $activeCountLimit = 10;
        
        /*检查未完成的任务情况*/
        $downloaderList = DownloaderModel::where('status', 1)->get();
        foreach ($downloaderList as $item) {
            $torrentTaskNum = 0;
            $torrentTaskSpace = 0;
            $activeTaskCount = 0; // 活跃任务数量
            
            // 获取下载器的种子信息
            $qb = \plugin\csauto\app\service\QBittorrentService::createService($item->id);
            $activeTorrents = [];
            if ($qb) {
                $torrentsList = $qb->getTorrents();
                foreach ($torrentsList as $torrent) {
                    // 判断是否为活跃任务：下载速度大于阈值（阈值单位为MB/s，dlspeed单位为字节/秒）
                    $dlSpeedMB = ($torrent['dlspeed'] ?? 0) / (1024 * 1024);
                    if ($dlSpeedMB > $activeSizeThreshold) {
                        $activeTaskCount++;
                        $activeTorrents[] = $torrent['hash'];
                    }
                }
            }
            
            $torrentTaskData = TorrentTaskModel::where('downloader_id', $item->id)->where('status', '>=', 1)->where('status', '<', 99)->where('down_status', '>', 0)->get();
            foreach ($torrentTaskData as $taskItem) {
                if ($taskItem->status == 1) $torrentTaskNum++;
                $torrentData = TorrentListService::getTorrentListData($taskItem->site_id, $taskItem->torrent_id);
                if ($torrentData) {
                    $torrentTaskSpace += HelperService::convertToGB($torrentData->torrents_size);
                }
            }
//            $torrentTaskNum = TorrentTaskModel::where('downloader_id', $item->id)->where('status', 1)->where('do', '<', 99)->where('down_status', '>', 0)->count();
            $effectiveTaskLimit = $item->getEffectiveTaskLimit();
            if (intval($effectiveTaskLimit) < 1) $effectiveTaskLimit = 999;
            if (intval($item->task_size) < 1) $item->task_size = 99999;
            addlog("下载器 ID：{$item->id}", "当前任务：$torrentTaskNum 条,Max：" . $effectiveTaskLimit . "条");
            addlog("下载器 ID：{$item->id}", "当前容量：$torrentTaskSpace GB ,Max：" . $item->task_size . "GB");
            addlog("下载器 ID：{$item->id}", "活跃任务：$activeTaskCount 个,Max：" . $activeCountLimit . "个（速度>{$activeSizeThreshold}MB/s）");
            // 展示任务种子体积范围
            $minSizeGb = intval($item->task_torrent_min_size ?? 0);
            $maxSizeGb = intval($item->task_torrent_max_size ?? 0);
            if ($minSizeGb > 0 || $maxSizeGb > 0) {
                $rangeText = ($minSizeGb > 0 ? $minSizeGb : 0) . "~" . ($maxSizeGb > 0 ? $maxSizeGb : '∞');
                addlog("下载器 ID：{$item->id}", "任务体积范围：{$rangeText} GB（设置则仅分配落在范围内的任务）");
            } else {
                addlog("下载器 ID：{$item->id}", "任务体积范围：未设置（不限制）");
            }
            
            // 增加活跃任务数量的判断条件
            if ($activeTaskCount >= $activeCountLimit) {
                addlog("下载器 ID：{$item->id}", "活跃任务数量达到限制，暂不分配新任务");
                continue;
            }
            
            if ($torrentTaskNum < $effectiveTaskLimit && $torrentTaskSpace < $item->task_size) {
                DownloaderWorkService::addDownloadTask($item);
            }
        }
        return '任务调用：' . date('Y-m-d H:i:s') . "\n";
    }

    /**
     * 停止/删除定时器
     *
     * @return bool
     */
    public function stop()
    {
        return Timer::del($this->timer);
    }

}